<template>
  <div id="app">
    <!-- 组件入口 -->
    <top-nav v-if="!$route.meta.hidenav"></top-nav>
    <!-- <div class="header"></div> -->
    <transition enter-active-class="animate__animated animate__backInLeft">
        <router-view @play="play" @playall="playall" ></router-view>
    </transition>

    <transition enter-active-class="animate__animated animate__slideInLeft">
		<music-play v-if="music" :music="music" :playCollect="playCollect" @changemusic="changeMusic"
				@changecircle="changecircle" :cirlceMode="cirlceMode" @play="play"></music-play>
		</transition>
  </div>
</template>
<script>
import TopNav from '@/components/TopNav.vue'
import MusicPlay from '@/components/MusicPlay.vue'

export default {
  data() {
    return {
      music: null,
      playCollect: [], //播放列表
      cirlceMode: "list", //list 列表循环, single单曲循环 random随机播放
    }
  },
  methods: {
    play(song) {
      this.music = song; //播放点击的音乐
      // this.playCollect.push(song);
      //把点击播放的音乐存入播放列表数组
      let isExit = false;
      for (let i = 0; i < this.playCollect.length; i++) {
        if (this.playCollect[i].id == song.id) { //在播放列表存在
          isExit = true;
          break;
        }
      }
      if (isExit) {
        // alert("该歌曲已经存在播放列表!");
      } else {
        this.playCollect.push(song);
      }
    },
    changeMusic(i) {
      let currentIndex = 0;
      this.playCollect.forEach((item, index) => {
        if (item.id == this.music.id) {
          currentIndex = index; //找到当前播放音乐的下标
        }
      });
      //判断播放模式
      if (this.cirlceMode == 'single') { //单曲循环
        this.music = {
          ...this.playCollect[currentIndex]
        }; //当前音乐生成一个新的对象
        return;
      } else if (this.cirlceMode == 'random') { //随机播放
        let random = Math.random() * (this.playCollect.length); //生成一个随机数-->Math.random() 0-数组长度
        random = Math.floor(random);
        this.music = this.playCollect[random];
        return;
      }
      //以下就是列表循环的时候的上一曲下一曲逻辑
      if (i == 1) { //上一曲
        currentIndex--;
        if (currentIndex < 0 && !this.playCollect[currentIndex]) { //当上一曲的下标小于0 应该波最后一个
          currentIndex = this.playCollect.length - 1;
        }
      } else if (i == 2) { //下一曲
        currentIndex++;
        //当下一曲的下标大于总播放列长度的时候 应该播放第一曲
        if (currentIndex > this.playCollect.length - 1 && !this.playCollect[currentIndex]) {
          currentIndex = 0;
        }
      }
      this.music = this.playCollect[currentIndex];
    },
    playall(songs) {
      this.playCollect = songs;
      this.music = songs[0];
    },
    changecircle(circle) { //设置 循环模式
      this.cirlceMode = circle;
    }
  },
  components: {
    TopNav,
    MusicPlay
  }
}
</script>
<style lang="less" scoped>
// .header{
//   height: 40px;
// }
</style>

